package com.marketing.auth.controller;

import com.marketing.auth.dto.*;
import com.marketing.auth.service.UserManagementService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户管理控制器
 * 提供用户的增删改查等管理功能
 */
@RestController
@RequestMapping("/users")
public class UserManagementController {

    private static final Logger logger = LoggerFactory.getLogger(UserManagementController.class);

    @Autowired
    private UserManagementService userManagementService;

    /**
     * 创建用户
     */
    @PostMapping
    public ResponseEntity<Map<String, Object>> createUser(
            @Valid @RequestBody CreateUserRequest request,
            @RequestHeader(value = "X-Operator", defaultValue = "system") String operator) {
        
        logger.info("收到创建用户请求，用户名: {}, 操作者: {}", request.getUsername(), operator);
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            UserInfoDto userInfo = userManagementService.createUser(request, operator);
            
            response.put("success", true);
            response.put("message", "用户创建成功");
            response.put("data", userInfo);
            
            logger.info("用户创建成功，用户名: {}, 用户ID: {}, 操作者: {}", 
                    request.getUsername(), userInfo.getId(), operator);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("创建用户失败，用户名: {}, 操作者: {}, 异常: {}", 
                    request.getUsername(), operator, e.getMessage(), e);
            
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 根据ID获取用户详情
     */
    @GetMapping("/{userId}")
    public ResponseEntity<Map<String, Object>> getUserById(@PathVariable Long userId) {
        logger.debug("收到获取用户详情请求，用户ID: {}", userId);
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            UserInfoDto userInfo = userManagementService.getUserById(userId);
            
            if (userInfo == null) {
                response.put("success", false);
                response.put("message", "用户不存在");
                return ResponseEntity.notFound().build();
            }
            
            response.put("success", true);
            response.put("message", "获取用户详情成功");
            response.put("data", userInfo);
            
            logger.debug("获取用户详情成功，用户ID: {}, 用户名: {}", userId, userInfo.getUsername());
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("获取用户详情失败，用户ID: {}, 异常: {}", userId, e.getMessage(), e);
            
            response.put("success", false);
            response.put("message", "获取用户详情失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 根据用户名获取用户详情
     */
    @GetMapping("/by-username/{username}")
    public ResponseEntity<Map<String, Object>> getUserByUsername(@PathVariable String username) {
        logger.debug("收到根据用户名获取用户详情请求，用户名: {}", username);
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            UserInfoDto userInfo = userManagementService.getUserByUsername(username);
            
            if (userInfo == null) {
                response.put("success", false);
                response.put("message", "用户不存在");
                return ResponseEntity.notFound().build();
            }
            
            response.put("success", true);
            response.put("message", "获取用户详情成功");
            response.put("data", userInfo);
            
            logger.debug("根据用户名获取用户详情成功，用户名: {}, 用户ID: {}", username, userInfo.getId());
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("根据用户名获取用户详情失败，用户名: {}, 异常: {}", username, e.getMessage(), e);
            
            response.put("success", false);
            response.put("message", "获取用户详情失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/{userId}")
    public ResponseEntity<Map<String, Object>> updateUser(
            @PathVariable Long userId,
            @Valid @RequestBody UpdateUserRequest request,
            @RequestHeader(value = "X-Operator", defaultValue = "system") String operator) {
        
        logger.info("收到更新用户请求，用户ID: {}, 操作者: {}", userId, operator);
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            UserInfoDto userInfo = userManagementService.updateUser(userId, request, operator);
            
            response.put("success", true);
            response.put("message", "用户更新成功");
            response.put("data", userInfo);
            
            logger.info("用户更新成功，用户ID: {}, 用户名: {}, 操作者: {}", 
                    userId, userInfo.getUsername(), operator);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("更新用户失败，用户ID: {}, 操作者: {}, 异常: {}", 
                    userId, operator, e.getMessage(), e);
            
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{userId}")
    public ResponseEntity<Map<String, Object>> deleteUser(
            @PathVariable Long userId,
            @RequestHeader(value = "X-Operator", defaultValue = "system") String operator) {
        
        logger.info("收到删除用户请求，用户ID: {}, 操作者: {}", userId, operator);
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            boolean success = userManagementService.deleteUser(userId, operator);
            
            if (success) {
                response.put("success", true);
                response.put("message", "用户删除成功");
                
                logger.info("用户删除成功，用户ID: {}, 操作者: {}", userId, operator);
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "用户不存在或删除失败");
                return ResponseEntity.badRequest().body(response);
            }
            
        } catch (Exception e) {
            logger.error("删除用户失败，用户ID: {}, 操作者: {}, 异常: {}", 
                    userId, operator, e.getMessage(), e);
            
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 批量删除用户
     */
    @DeleteMapping("/batch")
    public ResponseEntity<Map<String, Object>> batchDeleteUsers(
            @RequestBody List<Long> userIds,
            @RequestHeader(value = "X-Operator", defaultValue = "system") String operator) {
        
        logger.info("收到批量删除用户请求，用户ID列表: {}, 操作者: {}", userIds, operator);
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            int deletedCount = userManagementService.batchDeleteUsers(userIds, operator);
            
            response.put("success", true);
            response.put("message", String.format("批量删除完成，总数: %d, 成功: %d", userIds.size(), deletedCount));
            response.put("data", Map.of(
                    "total", userIds.size(),
                    "deleted", deletedCount,
                    "failed", userIds.size() - deletedCount
            ));
            
            logger.info("批量删除用户完成，总数: {}, 成功: {}, 操作者: {}", 
                    userIds.size(), deletedCount, operator);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("批量删除用户失败，操作者: {}, 异常: {}", operator, e.getMessage(), e);
            
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 重置用户密码
     */
    @PostMapping("/{userId}/reset-password")
    public ResponseEntity<Map<String, Object>> resetPassword(
            @PathVariable Long userId,
            @Valid @RequestBody ResetPasswordRequest request,
            @RequestHeader(value = "X-Operator", defaultValue = "system") String operator) {
        
        logger.info("收到重置密码请求，用户ID: {}, 操作者: {}", userId, operator);
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            boolean success = userManagementService.resetPassword(userId, request, operator);
            
            if (success) {
                response.put("success", true);
                response.put("message", "密码重置成功");
                
                logger.info("用户密码重置成功，用户ID: {}, 操作者: {}", userId, operator);
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "用户不存在或重置失败");
                return ResponseEntity.badRequest().body(response);
            }
            
        } catch (Exception e) {
            logger.error("重置密码失败，用户ID: {}, 操作者: {}, 异常: {}", 
                    userId, operator, e.getMessage(), e);
            
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 启用/禁用用户
     */
    @PutMapping("/{userId}/status")
    public ResponseEntity<Map<String, Object>> updateUserStatus(
            @PathVariable Long userId,
            @RequestParam Integer status,
            @RequestHeader(value = "X-Operator", defaultValue = "system") String operator) {
        
        logger.info("收到更新用户状态请求，用户ID: {}, 状态: {}, 操作者: {}", userId, status, operator);
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            if (status != 0 && status != 1) {
                response.put("success", false);
                response.put("message", "状态参数错误，只能是0(禁用)或1(启用)");
                return ResponseEntity.badRequest().body(response);
            }
            
            boolean success = userManagementService.updateUserStatus(userId, status, operator);
            
            if (success) {
                response.put("success", true);
                response.put("message", "用户状态更新成功");
                
                logger.info("用户状态更新成功，用户ID: {}, 状态: {}, 操作者: {}", 
                        userId, status, operator);
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "用户不存在或更新失败");
                return ResponseEntity.badRequest().body(response);
            }
            
        } catch (Exception e) {
            logger.error("更新用户状态失败，用户ID: {}, 状态: {}, 操作者: {}, 异常: {}", 
                    userId, status, operator, e.getMessage(), e);
            
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 分页查询用户列表
     */
    @GetMapping
    public ResponseEntity<Map<String, Object>> getUserList(@Valid UserQueryRequest request) {
        logger.debug("收到分页查询用户列表请求，查询条件: {}", request);
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            PageResult<UserInfoDto> result = userManagementService.getUserList(request);
            
            response.put("success", true);
            response.put("message", "查询用户列表成功");
            response.put("data", result);
            
            logger.debug("查询用户列表成功，总数: {}, 当前页: {}, 每页大小: {}", 
                    result.getTotal(), result.getCurrent(), result.getSize());
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("查询用户列表失败，查询条件: {}, 异常: {}", request, e.getMessage(), e);
            
            response.put("success", false);
            response.put("message", "查询用户列表失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 检查用户名是否存在
     */
    @GetMapping("/check-username")
    public ResponseEntity<Map<String, Object>> checkUsername(
            @RequestParam String username,
            @RequestParam(required = false) Long excludeUserId) {
        
        logger.debug("收到检查用户名请求，用户名: {}, 排除用户ID: {}", username, excludeUserId);
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            boolean exists;
            if (excludeUserId != null) {
                exists = userManagementService.isUsernameExist(username, excludeUserId);
            } else {
                exists = userManagementService.isUsernameExist(username);
            }
            
            response.put("success", true);
            response.put("message", "检查完成");
            response.put("data", Map.of(
                    "username", username,
                    "exists", exists
            ));
            
            logger.debug("用户名检查完成，用户名: {}, 存在: {}", username, exists);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("检查用户名失败，用户名: {}, 异常: {}", username, e.getMessage(), e);
            
            response.put("success", false);
            response.put("message", "检查用户名失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 检查邮箱是否存在
     */
    @GetMapping("/check-email")
    public ResponseEntity<Map<String, Object>> checkEmail(
            @RequestParam String email,
            @RequestParam(required = false) Long excludeUserId) {
        
        logger.debug("收到检查邮箱请求，邮箱: {}, 排除用户ID: {}", email, excludeUserId);
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            boolean exists;
            if (excludeUserId != null) {
                exists = userManagementService.isEmailExist(email, excludeUserId);
            } else {
                exists = userManagementService.isEmailExist(email);
            }
            
            response.put("success", true);
            response.put("message", "检查完成");
            response.put("data", Map.of(
                    "email", email,
                    "exists", exists
            ));
            
            logger.debug("邮箱检查完成，邮箱: {}, 存在: {}", email, exists);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("检查邮箱失败，邮箱: {}, 异常: {}", email, e.getMessage(), e);
            
            response.put("success", false);
            response.put("message", "检查邮箱失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }
}